module H8Bit.Tiles ( Tile(..)
                   , paintTile
                   , tile
                   , tileSurface
                   , tileSurfArr
                   , tileSurfArrWithEmpty
                   ) where

import Data.Array.IArray
import Graphics.UI.SDL.Rect
import Graphics.UI.SDL.Types
import Graphics.UI.SDL.Video

-- ^ The Tile type, just a Surface and the rectangle on this surface
data Tile = Tile {
    tBox  :: Rect,
    tSurf :: Surface
}

-- ^ Paint a single Tile on a Surface at position x y
paintTile :: Surface -> Int -> Int -> Tile -> IO Bool
paintTile s x y (Tile tr ts) = blitSurface ts (Just tr) s (Just $ Rect x y 0 0)

-- ^ Create a tile from a surface
tile :: Int -> Int -> Int -> Int -> Surface -> Tile
tile x y w h s = Tile { tBox=Rect x y w h, tSurf=s }


{-^ Tile a surface
  | w and h are the width and height of a tile! The whole surface is tiled.
-}
tileSurface :: Int -> Int -> Surface -> [Tile]
tileSurface w h s = let
  sWidth = surfaceGetWidth s
  sHeight = surfaceGetHeight s
  aTile x y | x < sWidth && y < sHeight = tile x y w h s : aTile (x + w) y
            | x >= sWidth && y < sHeight - h = aTile 0 (y + h)
            | otherwise = []
  in aTile 0 0

-- ^ Tile a surface but return an array for faster indexing.
tileSurfArr :: Int -> Int -> Surface -> Array Int Tile
tileSurfArr w h s = let ts = tileSurface w h s
                        lts = length ts
                    in listArray (0, lts) ts

-- ^ Tile a surface but return an array for faster indexing.
-- Add an empty element at index -1.
tileSurfArrWithEmpty :: Int -> Int -- Width and height
                     -> Surface -- Surface to cut from
                     -> Surface -- 'empty' surface at position -1
                     -> Array Int Tile
tileSurfArrWithEmpty w h s emptys = let ts = tileSurface w h s
                                        lts = length ts
                                    in listArray (-1, lts) (tile 0 0 w h emptys : ts)
